package com.ljh.account.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
//    通用的图片上传方法
public class Upload {
    @Value("${upload.path}")
    static private String uploadPath = "src/main/resources/static/uploads/";

    public static Object uploadImage(MultipartFile file, String category) {
        if (file.isEmpty()) {
            return null;
        }
        try {
            // 创建分类目录
            System.out.println("aaaa");
            File categoryDirectory = new File(uploadPath, category);
            if (!categoryDirectory.exists()) {
                categoryDirectory.mkdirs();
            }
            // 保存图片
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); // 添加时间戳以避免冲突
            Path filePath = Paths.get(categoryDirectory.getPath(), fileName);
            Files.copy(file.getInputStream(), filePath);
            // 返回图片路径
            HashMap<Object, Object> data = new HashMap<>();
            String url = "/images/" + category + "/" + fileName;
            data.put("url",url);
            return data;
        } catch (IOException e) {
            return null;
        }
    }
}
